import re
from xml.dom.minidom import parse
from openpyxl import load_workbook

from xlstoxml import write_to_string_file

languages_map = {'ar': 'ar', 'cs': 'cs', 'da': 'da', 'de': 'de', 'el': 'el',
                 'es': 'es', 'fi': 'fi', 'fr': 'fr', 'fr-rCA': 'fr-rCA', 'hu': 'hu',
                 'it': 'it', 'iw': 'iw', 'ja': 'ja', 'ko': 'ko', 'nl': 'nl',
                 'nb': 'nb', 'pl': 'pl', 'pt': 'pt', 'pt-rBR': 'pt-rBR', 'ro': 'ro',
                 'ru': 'ru', 'sk': 'sk', 'sv': 'sv', 'th': 'th', 'zh-rCN': 'zh',
                 'zh-rTW': 'zh-rTW'}
aosp_dir = '/home/nan/Project/Mini/android/packages/apps/'
lan_model_file = 'res/extract_lan_model.xlsx'


def main():
    # 键为语言key，值为name列
    lan_model_dict = {}
    wb = load_workbook(lan_model_file)
    ws = wb['Sheet1']
    # 遍历所有列获取key和gslan 序号，并装载到lan_model_dict
    for ri, row in enumerate(ws.rows):
        if ri == 0:
            continue
        key = row[0].value
        value = row[2].value
        if key is None or key == '':
            continue
        if value is None or value == '':
            continue
        lan_model_dict[key] = value

    # 遍历需要给定模块的的res，根据name提取字符串，并合入目标string文件
    for key in lan_model_dict.keys():
        value = lan_model_dict[key]
        index = value.find(',')
        module_name = value[:index]
        string_name = value[index + 1:]
        res_dir = aosp_dir + module_name + '/res/'
        for lan in languages_map.keys():
            lan_file = res_dir + 'values-' + lan + '/strings.xml'
            lans_dict = {}
            try:
                dom = parse(lan_file)
                for node in dom.getElementsByTagName('string'):
                    if node.getAttribute('name') == string_name:
                        lans_dict[key] = node.childNodes[0].nodeValue.strip('"')
                write_to_string_file('res/origin/values-' + languages_map[lan] + '/strings.xml', lans_dict)
            except FileNotFoundError:
                print('WARNING:', 'miss res file ' + lan_file + ', current name:' + string_name)


if __name__ == '__main__':
    main()
